const express = require('express')
const router = express.Router()
const InvitationService = require('../services/invitationService')
const ShareStatisticsService = require('../services/shareStatisticsService')
const InviteAnalyticsService = require('../services/inviteAnalyticsService')
const auth = require('../middleware/auth')
const logger = require('../utils/logger')

/**
 * 获取用户邀请码和分享信息
 */
router.get('/share-info', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const shareInfo = await InvitationService.getInviteShareInfo(userId)
    
    res.json({
      success: true,
      data: shareInfo
    })
  } catch (error) {
    logger.error('获取邀请分享信息失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取分享信息失败'
    })
  }
})

/**
 * 生成邀请二维码
 */
router.post('/qrcode', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const { baseUrl } = req.body
    
    const inviteCode = await InvitationService.getUserInviteCode(userId)
    const qrCodeDataUrl = await InvitationService.generateInviteQRCode(inviteCode, baseUrl)
    
    res.json({
      success: true,
      data: {
        inviteCode,
        qrCodeDataUrl
      }
    })
  } catch (error) {
    logger.error('生成邀请二维码失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '生成二维码失败'
    })
  }
})

/**
 * 处理邀请注册
 */
router.post('/register', async (req, res) => {
  try {
    const { 
      inviteCode, 
      userId, 
      shareChannel, 
      sharePlatform,
      deviceId 
    } = req.body
    
    if (!inviteCode || !userId) {
      return res.status(400).json({
        success: false,
        message: '邀请码和用户ID不能为空'
      })
    }
    
    // 收集额外数据用于防刷检查
    const extraData = {
      ipAddress: req.ip,
      userAgent: req.get('User-Agent'),
      shareChannel,
      sharePlatform,
      deviceId
    }
    
    const result = await InvitationService.handleInviteRegister(inviteCode, userId, extraData)
    
    if (result.success) {
      res.json({
        success: true,
        message: result.message,
        data: {
          invitation: result.invitation,
          needReview: result.needReview || false
        }
      })
    } else {
      res.status(400).json({
        success: false,
        message: result.message
      })
    }
  } catch (error) {
    logger.error('处理邀请注册失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '处理邀请注册失败'
    })
  }
})

/**
 * 获取邀请统计
 */
router.get('/stats', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const stats = await InvitationService.getInviteStats(userId)
    
    res.json({
      success: true,
      data: stats
    })
  } catch (error) {
    logger.error('获取邀请统计失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取邀请统计失败'
    })
  }
})

/**
 * 获取邀请详情列表
 */
router.get('/details', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const { page, limit, status } = req.query
    
    const options = {
      page: parseInt(page) || 1,
      limit: parseInt(limit) || 20,
      status: status || 'all'
    }
    
    const details = await InvitationService.getInviteDetails(userId, options)
    
    res.json({
      success: true,
      data: details
    })
  } catch (error) {
    logger.error('获取邀请详情失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取邀请详情失败'
    })
  }
})

/**
 * 获取邀请排行榜
 */
router.get('/ranking', async (req, res) => {
  try {
    const { limit, period, type } = req.query
    
    const options = {
      limit: parseInt(limit) || 50,
      period: period || 'all',
      type: type || 'count'
    }
    
    const ranking = await InvitationService.getInviteRanking(options)
    
    res.json({
      success: true,
      data: ranking
    })
  } catch (error) {
    logger.error('获取邀请排行榜失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取排行榜失败'
    })
  }
})

/**
 * 验证邀请码
 */
router.get('/validate/:code', async (req, res) => {
  try {
    const { code } = req.params
    const { channel = 'unknown', platform = 'unknown' } = req.query
    
    if (!code) {
      return res.status(400).json({
        success: false,
        message: '邀请码不能为空'
      })
    }
    
    const { User } = require('../models')
    const inviter = await User.findOne({
      where: { invitation_code: code },
      attributes: ['id', 'nickname', 'avatar']
    })
    
    if (!inviter) {
      return res.status(404).json({
        success: false,
        message: '邀请码无效'
      })
    }
    
    // 记录邀请链接点击
    await ShareStatisticsService.recordClick(code, channel, platform)
    
    res.json({
      success: true,
      data: {
        valid: true,
        inviter
      }
    })
  } catch (error) {
    logger.error('验证邀请码失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '验证邀请码失败'
    })
  }
})

/**
 * 记录分享行为
 */
router.post('/share', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const { 
      shareChannel, 
      sharePlatform = 'unknown',
      inviteCode 
    } = req.body
    
    if (!shareChannel || !inviteCode) {
      return res.status(400).json({
        success: false,
        message: '分享渠道和邀请码不能为空'
      })
    }
    
    const shareData = {
      userId,
      inviteCode,
      shareChannel,
      sharePlatform,
      ipAddress: req.ip,
      userAgent: req.get('User-Agent')
    }
    
    const result = await ShareStatisticsService.recordShare(shareData)
    
    res.json({
      success: true,
      message: '分享记录成功',
      data: result.data
    })
  } catch (error) {
    logger.error('记录分享行为失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '记录分享行为失败'
    })
  }
})

/**
 * 获取分享统计
 */
router.get('/share-stats', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const stats = await ShareStatisticsService.getUserShareStats(userId)
    
    res.json({
      success: true,
      data: stats
    })
  } catch (error) {
    logger.error('获取分享统计失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取分享统计失败'
    })
  }
})

/**
 * 获取推荐分享渠道
 */
router.get('/recommended-channels', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const recommendations = await ShareStatisticsService.getRecommendedChannels(userId)
    
    res.json({
      success: true,
      data: recommendations
    })
  } catch (error) {
    logger.error('获取推荐分享渠道失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取推荐分享渠道失败'
    })
  }
})

/**
 * 获取分享效果排行榜
 */
router.get('/share-ranking', async (req, res) => {
  try {
    const { period, limit } = req.query
    
    const options = {
      period: period || 'all',
      limit: parseInt(limit) || 20
    }
    
    const ranking = await ShareStatisticsService.getShareEffectivenessRanking(options)
    
    res.json({
      success: true,
      data: ranking
    })
  } catch (error) {
    logger.error('获取分享效果排行榜失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取分享效果排行榜失败'
    })
  }
})

/**
 * 获取用户风险统计
 */
router.get('/risk-stats', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const InviteAntiCheatService = require('../services/inviteAntiCheatService')
    const stats = await InviteAntiCheatService.getUserRiskStats(userId)
    
    res.json({
      success: true,
      data: stats
    })
  } catch (error) {
    logger.error('获取用户风险统计失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取用户风险统计失败'
    })
  }
})

/**
 * 获取待审核邀请列表（管理员）
 */
router.get('/pending-review', auth, async (req, res) => {
  try {
    // 检查管理员权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足'
      })
    }
    
    const { page = 1, limit = 20 } = req.query
    const offset = (page - 1) * limit
    
    const { User, Invitation } = require('../models')
    const { count, rows } = await Invitation.findAndCountAll({
      where: { status: 0 }, // 待审核状态
      include: [
        {
          model: User,
          as: 'inviter',
          attributes: ['id', 'nickname', 'phone']
        },
        {
          model: User,
          as: 'invitee',
          attributes: ['id', 'nickname', 'phone']
        }
      ],
      order: [['Invitation.created_at', 'DESC']],
      limit: parseInt(limit),
      offset
    })
    
    const invitations = rows.map(inv => ({
      id: inv.id,
      inviter: inv.inviter,
      invitee: inv.invitee,
      inviteCode: inv.invite_code,
      registerTime: inv.register_time,
      riskData: inv.risk_data ? JSON.parse(inv.risk_data) : null,
      createdAt: inv.created_at
    }))
    
    res.json({
      success: true,
      data: {
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(count / limit),
        invitations
      }
    })
  } catch (error) {
    logger.error('获取待审核邀请列表失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取待审核邀请列表失败'
    })
  }
})

/**
 * 审核邀请（管理员）
 */
router.post('/review/:id', auth, async (req, res) => {
  try {
    // 检查管理员权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足'
      })
    }
    
    const { id } = req.params
    const { action, reason } = req.body // action: approve, reject
    
    if (!['approve', 'reject'].includes(action)) {
      return res.status(400).json({
        success: false,
        message: '无效的审核操作'
      })
    }
    
    const { Invitation } = require('../models')
    const invitation = await Invitation.findByPk(id)
    if (!invitation) {
      return res.status(404).json({
        success: false,
        message: '邀请记录不存在'
      })
    }
    
    if (invitation.status !== 0) {
      return res.status(400).json({
        success: false,
        message: '该邀请已经审核过了'
      })
    }
    
    if (action === 'approve') {
      // 审核通过，发放奖励
      await invitation.update({ status: 1 })
      await InvitationService.grantRegisterReward(invitation.inviter_id, invitation.invitee_id)
      
      logger.info(`邀请审核通过: ID ${id}, 审核人 ${req.user.id}`)
    } else {
      // 审核拒绝
      await invitation.update({ 
        status: -1,
        review_reason: reason 
      })
      
      logger.info(`邀请审核拒绝: ID ${id}, 审核人 ${req.user.id}, 原因: ${reason}`)
    }
    
    res.json({
      success: true,
      message: action === 'approve' ? '审核通过' : '审核拒绝'
    })
  } catch (error) {
    logger.error('审核邀请失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '审核邀请失败'
    })
  }
})

/**
 * 获取邀请数据分析（管理员）
 */
router.get('/analytics', auth, async (req, res) => {
  try {
    // 检查管理员权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足'
      })
    }
    
    const { period, startDate, endDate } = req.query
    
    const options = {
      period: period || 'month',
      startDate,
      endDate
    }
    
    const analytics = await InviteAnalyticsService.getInviteAnalytics(options)
    
    res.json({
      success: true,
      data: analytics
    })
  } catch (error) {
    logger.error('获取邀请数据分析失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取邀请数据分析失败'
    })
  }
})

/**
 * 获取推广大使列表
 */
router.get('/ambassadors', auth, async (req, res) => {
  try {
    const { minInvites, minConversionRate, limit } = req.query
    
    const options = {
      minInvites: parseInt(minInvites) || 20,
      minConversionRate: parseInt(minConversionRate) || 30,
      limit: parseInt(limit) || 50
    }
    
    const ambassadors = await InviteAnalyticsService.getPromotionAmbassadors(options)
    
    res.json({
      success: true,
      data: ambassadors
    })
  } catch (error) {
    logger.error('获取推广大使列表失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取推广大使列表失败'
    })
  }
})

/**
 * 生成邀请效果报表（管理员）
 */
router.get('/report', auth, async (req, res) => {
  try {
    // 检查管理员权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足'
      })
    }
    
    const { period, format } = req.query
    
    const options = {
      period: period || 'month',
      format: format || 'summary'
    }
    
    const report = await InviteAnalyticsService.generateInviteReport(options)
    
    res.json({
      success: true,
      data: report
    })
  } catch (error) {
    logger.error('生成邀请效果报表失败:', error)
    res.status(500).json({
      success: false,
      message: error.message || '生成邀请效果报表失败'
    })
  }
})

module.exports = router